package com.googlecode.cswish.util;

import java.util.Collection;
import java.util.Date;

import com.googlecode.cswish.annotation.GenericType;
import com.googlecode.cswish.struts.spring.BeanIntrospector;
import com.googlecode.cswish.struts.spring.ObjectFactory;
import com.opensymphony.xwork2.ActionContext;

/**
 * Provide some simple functions to help get the class information
 * 
 * @author feng Date: 2009-5-24
 *
 */
public class ClassUtil {

	public static boolean isCollection(Class<?> classType) {
		return classType != null && Collection.class.isAssignableFrom(classType);
	}
	
	public static boolean isSimpleObj(Class<?> classType) {
		boolean isSimpleObj = classType != null && (classType.isPrimitive() || Number.class.isAssignableFrom(classType)
		|| String.class.equals(classType) || Date.class.isAssignableFrom(classType) 
		|| Boolean.class.equals(classType) || Byte.class.equals(classType));
		return isSimpleObj;
	}
	
	/**
	 * Get the class type according to the parameter information or action information
	 * 
	 * @return class name
	 */
	public static String getRuntimeType(String genericTypeName) {
		String typeName = null;
		if (genericTypeName == GenericType.MODEL) {
			ActionContext context = ActionContext.getContext();
			String actionName = context.getActionInvocation().getAction().getClass().getName();
			BeanIntrospector beanIntrospector = ObjectFactory.getInstance().getBean(BeanIntrospector.class, false);
			typeName = beanIntrospector.getModelName(beanIntrospector.getSimpleName(actionName));
			// TODO: cache the typeName?
		} else if (genericTypeName == GenericType.PARAM_MODEL) {
			ActionContext context = ActionContext.getContext();
			Object type = context.getParameters().get(FrameConstant.PARAM_GENERIC_TYPE);
			
			if (type != null && type instanceof String[]) {
				String[] types = (String[]) type;
				if (types.length > 0) {
					typeName = types[0];
				}
			}
		} else {
			typeName = genericTypeName;
		}
		
		return typeName;
	}
}